package com.example.administrator.szb.activity.myyewu;

import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.example.administrator.szb.R;
import com.example.administrator.szb.activity.CJYWXQActivity;
import com.example.administrator.szb.adapter.BaseAdapter;
import com.example.administrator.szb.activity.base.BaseActivity;
import com.example.administrator.szb.bean.ResultBean;
import com.example.administrator.szb.bean.YWBQGLBean;
import com.example.administrator.szb.tinkerutil.SampleApplicationLike;
import com.example.administrator.szb.http.HttpUtil;
import com.example.administrator.szb.http.URLAddress;
import com.example.administrator.szb.util.GetJsonDataUtil;
import com.example.administrator.szb.util.ScreenExpressionUtils;
import com.example.administrator.szb.util.Toasts;
import com.example.zhouwei.library.CustomPopWindow;

import java.util.HashMap;
import java.util.Iterator;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by D N on 2017/10/10.
 */

public class YWGLYESActivity extends BaseActivity {
    @Bind(R.id.ywgl_yes_recyclerview)
    RecyclerView ywglYesRecyclerview;

    public static YWBQGLBean ywbqglBean;
    public static boolean isLoad = false;
    BaseAdapter<YWBQGLBean.DataBean> adapter;
    @Bind(R.id.ywgl_yes_button_del)
    Button ywglYesButtonDel;

    HashMap<Integer,Integer> checkbox_choose = new HashMap<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ywgl_yes_activity);
        ButterKnife.bind(this);
        initToolbarThree(R.id.ywgl_toolbar_include, "业务管理", "编辑", new Callback() {
            @RequiresApi(api = Build.VERSION_CODES.KITKAT)
            @Override
            public void doSomeThing() {
                showPopupwindow(R.layout.view_popupwindow_myzx, R.layout.ywgl_yes_activity);
            }
        });
        canRefresh = false;
        isLoad = true;
        requestData();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        isLoad = false;
    }

    public static boolean canRefresh = false;
    @Override
    protected void onResume() {
        super.onResume();
        if (canRefresh){
            requestData();
        }
    }

    private void requestData() {
        HashMap<String, String> map = new HashMap<>();
        map.put("code", HttpUtil.getParam());
        map.put("users_id", SampleApplicationLike.getUserloginInstance().getId() + "");
        String json = GetJsonDataUtil.simpleMapToJsonStr(map);
        HttpUtil.RequestGsonPost(SampleApplicationLike.getQueueInstance(), Request.Method.POST, YWBQGLBean.class, URLAddress.URLBASE + URLAddress.URL_YWBQGL, map, new Response.Listener() {
            @Override
            public void onResponse(Object response) {
                ywbqglBean = (YWBQGLBean) response;
                if (ywbqglBean.getResult() == 1) {
                    initRecyclerView();
                    if (ywbqglBean.getData().size() == 0){
                        startActivity(new Intent(YWGLYESActivity.this, YWGLNOActivity_new.class));
                        Toasts.show(YWGLYESActivity.this, "快去添加便签吧。。。", Toast.LENGTH_SHORT);
                        finish();
                    }
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                //startActivity(new Intent(YWGLYESActivity.this,YWGLNOActivity_new.class));
            }
        });
    }

    private void initRecyclerView() {
        ywglYesRecyclerview.setLayoutManager(new LinearLayoutManager(this));
        adapter = new BaseAdapter<YWBQGLBean.DataBean>(this, ywbqglBean.getData()) {
            @Override
            public void convert(final int position, BaseViewHolder holder, YWBQGLBean.DataBean dataBean) {
                if (dataBean.getShowCheckbox() == 0) {
                    ((CheckBox) holder.getView(R.id.checkBox4)).setVisibility(View.GONE);
                } else {
                    ((CheckBox) holder.getView(R.id.checkBox4)).setVisibility(View.VISIBLE);
                    ((CheckBox) holder.getView(R.id.checkBox4)).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                        @Override
                        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                            if (b){
                                checkbox_choose.put(position,1);
                            }else{
                                checkbox_choose.put(position,0);
                            }
                        }
                    });
                }



                if (dataBean.getNext().size() == 0){
                    (holder.getView(R.id.imageView21)).setVisibility(View.INVISIBLE);
                }

                ((TextView) holder.getView(R.id.textView52)).setText(dataBean.getTitle());
            }

            @Override
            public int getLayoutId(int viewType) {
                return R.layout.view_ywbqgl_item;
            }
        };
        adapter.setOnItemClickListener(new BaseAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                int visible = view.findViewById(R.id.checkBox4).getVisibility();

                if (visible == 0){
                    //boolean flag = ((CheckBox)view.findViewById(R.id.checkBox4)).isClickable();
                    int flag = ywbqglBean.getData().get(position).getShowCheckbox();
                    if (flag == 0){
                        ((CheckBox)view.findViewById(R.id.checkBox4)).setChecked(false);
                        checkbox_choose.put(position,0);
                        ywbqglBean.getData().get(position).setShowCheckbox(1);
                    }else {
                        ((CheckBox)view.findViewById(R.id.checkBox4)).setChecked(true);
                        ywbqglBean.getData().get(position).setShowCheckbox(0);
                        checkbox_choose.put(position,1);
                    }
                }else{
                    if (ywbqglBean.getData().get(position).getNext().size() > 0){
                        Intent intent = new Intent(YWGLYESActivity.this,CJYWXQActivity.class);
                        intent.putExtra("title",ywbqglBean.getData().get(position).getTitle());
                        intent.putExtra("position",position);
                        startActivity(intent);
                    }else{

                    }
                }


            }
        });
        ywglYesRecyclerview.setAdapter(adapter);
    }


    /**
     * 初始化popupwindow弹出框
     */
    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
    private void showPopupwindow(int view_layout_id, int rootview_layout_id) {
        View popwindow_view = LayoutInflater.from(this).inflate(view_layout_id, null);
        ((TextView) popwindow_view.findViewById(R.id.view_my_zx_twzx)).setText("修改");
        ((TextView) popwindow_view.findViewById(R.id.view_my_zx_spzx)).setText("删除");
        View rootview = LayoutInflater.from(this).inflate(rootview_layout_id, null);

        //如果不是进度框，就执行底部弹出
        if (view_layout_id != R.layout.view_progressbar) {
            popWindow = new CustomPopWindow.PopupWindowBuilder(this)
                    .setView(popwindow_view)//显示的布局，还可以通过设置一个View
                    .create()//创建PopupWindow
                    .showAtLocation(rootview, Gravity.TOP | Gravity.RIGHT, ScreenExpressionUtils.dip2px(this, 10), ScreenExpressionUtils.dip2px(this, 70));
            handleLogic(popwindow_view, popWindow);//处理popupwindow 中的item点击事件
        }
        //显示PopupWindow

    }


    /**
     * 处理弹出显示内容、点击事件等逻辑
     *
     * @param contentView
     */
    private void handleLogic(View contentView, final CustomPopWindow mCustomPopWindow) {
        View.OnClickListener listener = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mCustomPopWindow != null) {
                    mCustomPopWindow.dissmiss();
                }
                switch (v.getId()) {
                    case R.id.view_my_zx_twzx:
                       // finish();
                        startActivity(new Intent(YWGLYESActivity.this, YWGLNOActivity_new.class));

                        break;
                    case R.id.view_my_zx_spzx:
                        for (int i = 0; i < ywbqglBean.getData().size(); i++) {
                            ywbqglBean.getData().get(i).setShowCheckbox(1);
                        }
                        adapter.notifyDataSetChanged();
                        ywglYesButtonDel.setVisibility(View.VISIBLE);
                        initToolbarThree(R.id.ywgl_toolbar_include, "业务管理", "取消",  new Callback() {
                            @Override
                            public void doSomeThing() {
                                for (int i = 0; i < ywbqglBean.getData().size(); i++) {
                                    ywbqglBean.getData().get(i).setShowCheckbox(0);
                                }
                                adapter.notifyDataSetChanged();
                                ywglYesButtonDel.setVisibility(View.GONE);

                                initToolbarThree(R.id.ywgl_toolbar_include, "业务管理", "编辑", new Callback() {
                                    @RequiresApi(api = Build.VERSION_CODES.KITKAT)
                                    @Override
                                    public void doSomeThing() {
                                        showPopupwindow(R.layout.view_popupwindow_myzx, R.layout.ywgl_yes_activity);
                                    }
                                });


                            }
                        });
                        break;
                }
                //Toasts.show(MingPianActivity.this, showContent, Toast.LENGTH_SHORT);
            }
        };
        contentView.findViewById(R.id.view_my_zx_twzx).setOnClickListener(listener);
        contentView.findViewById(R.id.view_my_zx_spzx).setOnClickListener(listener);

    }

    @OnClick(R.id.ywgl_yes_button_del)
    public void onViewClicked() {
       try {
           String id_info = "";
           Iterator<Integer> it = checkbox_choose.keySet().iterator();
           while (it.hasNext()){
               int flag = it.next();
               if (checkbox_choose.get(flag) == 1){
                   id_info = id_info+ywbqglBean.getData().get(flag).getId() +",";
               }
           }
           doDel(id_info);//删除业务标签
       }catch (Exception e){
           Toasts.show(this, "快去添加一些业务标签吧...", Toast.LENGTH_SHORT);
       }
    }

    private void doDel(String id_info) {
        HashMap<String,String> map = new HashMap<>();
        map.put("code",HttpUtil.getParam());
        map.put("users_id",""+SampleApplicationLike.getUserloginInstance().getId());
        map.put("business_id",id_info);
        HttpUtil.RequestGsonPost(SampleApplicationLike.getQueueInstance(), Request.Method.POST, ResultBean.class, URLAddress.URLBASE + URLAddress.URL_DELYWBQ, map, new Response.Listener() {
            @Override
            public void onResponse(Object response) {
                ResultBean resultBean = (ResultBean) response;
                if (resultBean.getResult() == 1){
                    //finish();
                    ywbqglBean = null;
                    /*Intent intent = new Intent(YWGLYESActivity.this, YWGLYESActivity.class);
                    //SampleApplicationLike.getQueueInstance().cancelAll("tag");
                    intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                    startActivity(intent);
                    overridePendingTransition(0, 0);*/
                    requestData();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
    }

}
